#include <QtGui>
#include <QSqlDatabase>
#include <QString>
#include <QSqlQuery>

#include "include/addUsr.h"

AddUsr::AddUsr(QWidget *parent)
    : QDialog(parent)
{
    setWindowFlags(Qt::FramelessWindowHint);
    CreateWidget();
    CreateLayout();

    setWindowTitle(QString::fromUtf8("新增用户"));
    setFixedSize(sizeHint());
}

void AddUsr::CreateWidget()
{
    bannerLabel = new QLabel(QString::fromUtf8("新增用户"), this);
    QFont tmpFont = bannerLabel->font();
    tmpFont.setPointSize(18);
    tmpFont.setBold(true);
    bannerLabel->setFont(tmpFont);

    usrNameLabel = new QLabel(QString::fromUtf8("用户名:"), this);
    pwdLabel = new QLabel(QString::fromUtf8(" 密码:"), this);
    usrNameLineEdit = new QLineEdit(this);
    pwdLineEdit = new QLineEdit(this);
    saveBtn = new QPushButton(QString::fromUtf8("保存"), this);
    cancleBtn = new QPushButton(QString::fromUtf8("取消"), this);

    bannerLabel->setAlignment(Qt::AlignCenter);

    pwdLineEdit->setEchoMode(QLineEdit::Password);

    connect(saveBtn, SIGNAL(clicked()), this, SLOT(Save()));
    connect(cancleBtn, SIGNAL(clicked()), this, SLOT(close()));
}

void AddUsr::CreateLayout()
{
    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->addWidget(bannerLabel, 0, 1, 2, 4);
    mainLayout->addWidget(usrNameLabel, 2, 0, 1, 1);
    mainLayout->addWidget(usrNameLineEdit, 2, 1, 1, 5);
    mainLayout->addWidget(pwdLabel, 3, 0, 1, 1);
    mainLayout->addWidget(pwdLineEdit, 3, 1, 1, 5);
    mainLayout->addWidget(saveBtn, 5, 4, 1, 1);
    mainLayout->addWidget(cancleBtn, 5, 5, 1, 1);

    setLayout(mainLayout);
}

void AddUsr::Save()
{
    qDebug() << "123";
    QSqlDatabase::database().transaction();
    QSqlQuery query;

    QString usrNameTmp = usrNameLineEdit->text();
    QString pwdTmp = pwdLineEdit->text();

    query.exec(QString("insert into usrInfo values('%1', '%2')").arg(usrNameTmp).arg(pwdTmp));

    QSqlDatabase::database().commit();

    accept();
    this->close();
}
